/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package messages;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

import ippacket.Header;
import ippacket.Packet;

/**
 *
 * @author chuda
 */
public class MessageSender extends Thread{
    private Header header;
    private DatagramSocket socket;
    private int port;
    private String pacote, ipAddress;


    public MessageSender( String ipAddress, String pacote, int port) {
        this.port = 49552;
        this.ipAddress = "localhost";
        this.pacote = pacote;
        this.start();
    }

    @Override
    public void run() {
        try {
            socket = new DatagramSocket();
            InetAddress host = InetAddress.getByName(ipAddress);
            Packet p = new Packet();
            p.setContent(pacote);
            p.addHeader(new Header(this.ipAddress));
            byte[] message = p.toString().getBytes();
            DatagramPacket request = new DatagramPacket(message,message.length, host, port);

            System.out.println("vou mandar mensagem "+ p.toString());
            socket.send(request);
            socket.close();
            
        } catch (SocketException e) {
            System.out.println("Socket: " + e.getMessage());
        } catch (IOException e) {
            System.out.println("IO: " + e.getMessage());
        }
    }
}
